﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using KeRui.BLL;
using System.Text;
using KeRui.Common;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using KeRui.TemplateMaker;

public partial class Manage_Cms_ContentMove : System.Web.UI.Page
{
    protected int SiteID = PageRequest.GetInt("siteid",-1);
    protected int NodeID = PageRequest.GetInt("nodeid", -1);
    protected string acttype = PageRequest.GetString("acttype");
    protected int newNodeID;
    protected string ContentIDs = PageRequest.GetString("contentids");
    public string act = PageRequest.GetString("act").ToLower().Trim();
    KeRui.BLL.CmsContent bllCmsContent = new CmsContent();
    KeRui.BLL.CmsNode bllCmsNode = new CmsNode();
    protected void Page_Load(object sender, EventArgs e)
    {
        ManageHelper.CheckAdminLogin();
        ManageHelper.CheckAdminPower("site_contentmove_" + SiteID);
        //输出被迁移的数据内容
        if (act == "move")
        {
            move();
        }
        else if (act == "copy")
        {
            copy();
        }
    }

    protected void copy()
    {
        //获得所有新闻,ContentIDs
        //获得复制去向
        string nodeIDCollection = PageRequest.GetString("NodeIDCollectionToMove");
        if (nodeIDCollection.IndexOf(",") > 0)
        {
            Response.Redirect("ContentMove.aspx?acttype=copy&siteid=" + SiteID + "&nodeid=" + NodeID + "&contentids=" + ContentIDs + "&sucmsg=数据前往的栏目只能选择一个");
            Response.End();
        }
        if (!string.IsNullOrEmpty(nodeIDCollection))
        {
            ManageHelper.CheckAdminPower("site_contentadd_" + SiteID);//检查是否有添加权限HYC
            foreach (string contentid in ContentIDs.Split(','))
            {
                if (contentid != "")
                {
                    //获得新闻信息
                    KeRui.Model.CmsContent modelCmsContent = new KeRui.Model.CmsContent();
                    KeRui.Model.CmsNode modelCmsNode = new KeRui.Model.CmsNode();
                    modelCmsContent = bllCmsContent.GetModel(Convert.ToInt32(contentid));
                    modelCmsNode = bllCmsNode.GetModel(Convert.ToInt32(nodeIDCollection));
                    if (modelCmsNode == null)
                    {
                        Response.Redirect("ContentMove.aspx?acttype=copy&siteid=" + SiteID + "&nodeid=" + NodeID + "&contentids=" + ContentIDs + "&sucmsg=未找到栏目，可能已经被删除。");
                        Response.End();
                    }
                    //模拟添加新闻
                    #region 添加文章
                    //添加Content，需要动态构建SQL语句
                    //添加Content的通用字段
                    modelCmsContent.NodeID = modelCmsNode.NodeID;
                    modelCmsContent.UserID = KeRui.BLL.Account.GetLoginUserID();
                    string[] ss = modelCmsNode.ContentDefaultTemplateFile.Split('\\');
                    modelCmsContent.TemplateFile = ss[(ss.Length - 1)];//获得栏目的内容模版
                    modelCmsContent.NextID = 0;
                    modelCmsContent.PrevID = 0;
                    //存储路径处理，前台可能需要自定义路径
                    modelCmsContent.FileDir = "";
                    modelCmsContent.FilePath = "";
                    modelCmsContent.PicUrl = "";
                    int newcontentid = bllCmsContent.Add(modelCmsContent);//复制后的新ID
                    //获得数据附加模型字段
                    DataRow drCmsContentShow = bllCmsContent.GetModelByContentID(modelCmsContent.ContentID, "").Tables[0].Rows[0];
                    KeRui.BLL.CmsField bllCmsField = new KeRui.BLL.CmsField();
                    List<KeRui.Model.CmsField> listCmsField = new List<KeRui.Model.CmsField>();
                    listCmsField = bllCmsField.GetList("ModelID=" + modelCmsContent.ModelID + "AND IsUsing='True' AND FieldName!='ContentID'");
                    //动态的数据写入，插入到对应的Content表
                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("INSERT INTO CmsContent{0} ", modelCmsContent.ModelID);
                    string item = " ( ";
                    string value = " ( ";
                    item += "ContentID,";
                    value += newcontentid + ",";
                    for (int i = 0; i < listCmsField.Count; i++)
                    {
                        //获得字段名称，类型进行增加判断
                        switch (listCmsField[i].FieldType)
                        {

                            case 8: if (i == listCmsField.Count - 1)
                                {
                                    item += listCmsField[i].FieldName + ") ";
                                    value += drCmsContentShow[listCmsField[i].FieldName].ToString() + ") ";
                                }
                                else
                                {
                                    item += listCmsField[i].FieldName + ",";
                                    value += drCmsContentShow[listCmsField[i].FieldName].ToString() + ",";
                                }
                                break;
                            default: if (i == listCmsField.Count - 1)
                                {
                                    item += listCmsField[i].FieldName + ") ";
                                    value += "'" + drCmsContentShow[listCmsField[i].FieldName].ToString() + "') ";
                                }
                                else
                                {
                                    item += listCmsField[i].FieldName + ",";
                                    value += "'" + drCmsContentShow[listCmsField[i].FieldName].ToString() + "',";
                                }
                                break;
                        }
                    }
                    sb.Append(item);
                    sb.Append(" VALUES ");
                    sb.Append(value);
                    KeRui.BLL.Common.ExecuteSQL(sb.ToString()); //执行SQL语句

                    Publish publish = new Publish();
                    try
                    {
                        publish.PublishContent(newcontentid);
                        int preID = bllCmsContent.GetModel(newcontentid).PrevID;
                        int nextID = bllCmsContent.GetModel(newcontentid).NextID;
                        if (preID != 0)
                        {
                            publish.PublishContent(preID);
                        }
                        if (nextID != 0)
                        {
                            publish.PublishContent(nextID);
                        }
                    }
                    catch
                    {
                        Response.Write("生成错误，请重新发布。");
                        Response.End();
                    }
                    //日志记录HYC
                    ManageHelper.AddLog("site_contentadd_" + SiteID, "添加了文章：“" + modelCmsContent.Title + "”。");
                }
            }
            //完成后页面跳转
            Response.Redirect("ContentList.aspx?siteid=" + SiteID + "&nodeid=" + Convert.ToInt32(nodeIDCollection));
            Response.End();
            #endregion

        }
    }
    #region 迁移代码
    protected void move()
    {
        //删除原本文件下内容
        //前往数据库修改信息（移动数据的NodeID变更新的NodeID，原本节点ContentCount，新节点ContentCount）
        //生成移动后的内容
        string nodeIDCollection = PageRequest.GetString("NodeIDCollectionToMove");
        
        if (nodeIDCollection.IndexOf(",") > 0)
        {
            Response.Redirect("ContentMove.aspx?acttype=move&siteid=" + SiteID + "&nodeid=" + NodeID + "&contentids=" + ContentIDs + "&sucmsg=数据前往的栏目只能选择一个");
            Response.End();
        }
        if (!string.IsNullOrEmpty(nodeIDCollection))
        {
            ManageHelper.AddLog("site_contentmove_" + SiteID, "开始迁移数据，ID为" + ContentIDs + "迁移到节点：" + newNodeID);
            //移动部分文件
            //删除原本文件
            newNodeID = Convert.ToInt32(nodeIDCollection);
            if (ContentIDs != "" && NodeID != -1)
            {


                string[] IDs = Utils.SplitString(ContentIDs, ",");
                string dirIDs = bllCmsNode.GetModel(NodeID).NodeDir;
                int num = 0;
                for (int i = 0; i < IDs.Length - 1; i++)
                {
                    string fileIDs = dirIDs + "\\" + Convert.ToInt32(IDs[i]) + ".shtml";
                    if (File.Exists(fileIDs))
                    {
                        File.Delete(fileIDs);
                    }
                    bllCmsContent.FixPreNextID(Convert.ToInt32(IDs[i]), "delete");
                    num++;
                }
                //前往数据库
                bllCmsContent.MoveContentByContentID(ContentIDs.Remove(ContentIDs.Length - 1), NodeID, newNodeID, num);

                //生成文件
                Publish publish = new Publish();
                try
                {
                    for (int i = 0; i < IDs.Length - 1; i++)
                    {
                        publish.PublishContent(Convert.ToInt32(IDs[i]));
                        int preID = bllCmsContent.GetModel(Convert.ToInt32(IDs[i])).PrevID;
                        int nextID = bllCmsContent.GetModel(Convert.ToInt32(IDs[i])).NextID;
                        if (preID != 0)
                        {
                            publish.PublishContent(preID);
                        }
                        if (nextID != 0)
                        {
                            publish.PublishContent(nextID);
                        }
                    }
                }
                catch
                {
                    Response.Write("生成错误，请重新发布。");
                    Response.End();
                }
                ManageHelper.AddLog("site_contentmove_" + SiteID, "迁移了数据，ID为" + ContentIDs + "迁移到节点：" + newNodeID);
                Response.Redirect("ContentList.aspx?siteid=" + SiteID + "&nodeid=" + newNodeID + "&sucmsg=迁移成功。");
                Response.End();
            }

            else if (NodeID != -1 && ContentIDs == "")
            {
                //移动节点全部，删除原本文件下内容
                //获得所有.shtml文件

                string dir = bllCmsNode.GetModel(NodeID).NodeDir;
                string[] foldernames = Directory.GetFiles(dir, "*.shtml");
                DataTable ContentIDarry = bllCmsContent.GetContentIDByNodeID(NodeID);
                //前往数据库
                bllCmsContent.MoveContentByNodeID(NodeID, newNodeID);
                foreach (string foldername in foldernames)//删除开始
                {
                    if (File.Exists(foldername))
                    {
                        File.Delete(foldername);
                    }
                }


                //生成移动后的内容
                Publish publish = new Publish();
                try
                {
                    for (int i = 0; i < ContentIDarry.Rows.Count; i++)
                    {
                        publish.PublishContent(Convert.ToInt32(ContentIDarry.Rows[i][0]));
                        int preID = bllCmsContent.GetModel(Convert.ToInt32(ContentIDarry.Rows[i][0])).PrevID;
                        int nextID = bllCmsContent.GetModel(Convert.ToInt32(ContentIDarry.Rows[i][0])).NextID;
                        if (preID != 0)
                        {
                            publish.PublishContent(preID);
                        }
                        if (nextID != 0)
                        {
                            publish.PublishContent(nextID);
                        }
                    }
                }
                catch
                {
                    Response.Write("生成错误，请重新发布。");
                    Response.End();
                }
                ManageHelper.AddLog("site_contentmove_" + SiteID, "迁移了" + NodeID + "节点下的Content,迁往" + newNodeID + "节点。");
                Response.Redirect("ContentList.aspx?siteid=" + SiteID + "&nodeid=" + newNodeID + "&sucmsg=迁移成功。");
                Response.End();
            }
        }
    }
    #endregion

    #region 栏目下拉列表

    protected static string SelectNodeList(int pId, int intTemp)
    {
        string RetStr = "";
        CmsNode bllCmsNode = new CmsNode();
        List<KeRui.Model.CmsNode> list = bllCmsNode.GetListByPId(pId, PageRequest.GetInt("siteid", -1));
        int j = 0;
        foreach (KeRui.Model.CmsNode model in list)
        {
            j++;
            string Empty = "";
            for (int i = 0; i < model.Depth; i++)
            {
                Empty += "　";
            }
            if (model.NodeID == intTemp)
            {
                RetStr += "<option value=" + model.NodeID + " selected>" + Empty + "{0}" + model.NodeName + "</option>";
            }
            else
            {
                RetStr += "<option value=" + model.NodeID + ">" + Empty + "{0}" + model.NodeName + "</option>";
            }
            if (model.ChildNum > 0)
            {
                RetStr += SelectNodeList(model.NodeID, intTemp);
            }
            if (j == list.Count)
            {
                RetStr = RetStr.Replace("{0}", "└");
            }
            else
            {
                RetStr = RetStr.Replace("{0}", "├");
            }
        }
        return RetStr;
    }

    #endregion
}

